//
//  WBBaseViewController.swift
//  Swift_Weibo
//
//  Created by Tim on 2019/8/13.
//  Copyright © 2019 Tim. All rights reserved.
//  全局 父视图

import UIKit

class WBBaseViewController: UIViewController {
    
    /// 是否已经登录标识符
    var logon : Bool = true
    
    /// 访客视图信息
    var visitorInfo : [String : String]?
    
    /// 主表格视图，未登录时不需要创建该视图
    var tableView : UITableView = {
        let tableView = UITableView(frame: kScreenBounds, style: .plain)
        tableView.estimatedRowHeight = 0
        tableView.estimatedSectionFooterHeight = 0
        tableView.estimatedSectionHeaderHeight = 0
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        if #available(iOS 11.0, *) {
            tableView.contentInsetAdjustmentBehavior = .never
        } else {
            
        }
        tableView.contentInset = UIEdgeInsets(top: kNavigationBarHeight, left: 0, bottom: kTabBarHeight, right: 0)
        return tableView
    }()
    
    /// 加载控件
    var refreshControl : UIRefreshControl?
    
    /// 是不是上拉加载
    var isPullUp : Bool = false
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        automaticallyAdjustsScrollViewInsets = false
        setupUI()
        loadData()
    }
    
    /// 创建自定义导航栏
    let height = UIScreen.main.bounds.height
    
    lazy var navigationBar = WBNavigationBar(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kNavigationBarHeight))
    
    /// 懒加载导航栏项目
    lazy var navItem = UINavigationItem()
    
    /// 赋值自定义 item 的 title
    override var title: String? {
        didSet {
            navItem.title = title
        }
    }
}

// MARK: - 界面布局相关
extension WBBaseViewController {
    
    /// 界面布局
    private func setupUI() {
        view.backgroundColor = UIColor.white
        setupNavigationBar()
        logon ? setupTableView() : setupVisitorView()
    }
    
    /// 创建 导航条
    private func setupNavigationBar() {
        view.addSubview(navigationBar)
        navigationBar.items = [navItem]
    }
    
    
    /// 创建主表格视图, 设置页面 UI 可以重写这个方法
    /// 如果你想初始化的时候默认自带一个 TableView 请调用 super.setupTableView()
    @objc func setupTableView() {
        view.insertSubview(tableView, belowSubview: navigationBar)
        refreshControl = UIRefreshControl()
        tableView.addSubview(refreshControl!)
        refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
        
        // 添加上拉加载逻辑
        tableView.rx.willDisplayCell.subscribe(onNext: {[weak self](cell, indexPath) in
            // 当前行索引
            let currentRow = indexPath.row
            
            guard let weakSelf = self else {
                return
            }
            // 获取最大 section 索引
            let section = weakSelf.tableView.numberOfSections - 1
            
            if section < 0 || currentRow < 0 {
                return
            }
            
            let count = weakSelf.tableView.numberOfRows(inSection: section)
            
            if currentRow == (count - 1) && !(weakSelf.isPullUp) {
                weakSelf.isPullUp = true
                weakSelf.loadData()
            }
            
        })
        .disposed(by: disposeBag)
    }
    
    private func setupVisitorView() {
        let visitorView = WBVisitorView(frame: view.bounds)
        view.insertSubview(visitorView, belowSubview: navigationBar)
        
        // 添加访问者视图描述
        visitorView.visitorInfo = visitorInfo
        
        // 添加注册和登录的监听方法
        visitorView.registerBtn.addTarget(self, action: #selector(registerAction), for: .touchUpInside)
        visitorView.loginBtn.addTarget(self, action: #selector(loginAction), for: .touchUpInside)
        
        // 添加公共公共按钮在导航栏
        navItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: .plain, target: self, action: #selector(registerAction))
        navItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: .plain, target: self, action: #selector(loginAction))
    }
}


// MARK: - 数据相关
extension WBBaseViewController {
    @objc func loadData() {
        refreshControl?.endRefreshing()
    }
}


// MARK: - 访问者视图监听方法
extension WBBaseViewController {
    @objc private func registerAction() {
        // FIXME: - 注册逻辑未完善
        debugLog("进入注册逻辑")
    }
    
    @objc private func loginAction() {
        // FIXME: - 登录逻辑未完善
        debugLog("进入登录逻辑")
    }
}

/// 改变 _UIBarBackground 和 _UINavigationBarContentView 的 frame
class WBNavigationBar: UINavigationBar {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        barTintColor = UIColor(hex: 0xf6f6f6)
        tintColor = UIColor.orange
        titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.darkGray]
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        for subview in subviews {
            let subviewName = NSStringFromClass(subview.classForCoder)
            if subviewName == "_UIBarBackground" {
                subview.frame = bounds
            } else if subviewName == "_UINavigationBarContentView" {
                var frame = subview.frame
                frame.origin.y = kStatusBarHeight
                frame.size.height = bounds.height
                subview.frame = frame
            }
        }
    }
    
}
